package main
import (
	"net/http"
	"fmt"
	"io/ioutil"
	"strings"
	"time"
	"os"
	//"io"
)

func main(){
	var max = 1024
	/*
	var sgcc_url []string = []string{
		`http://ecp.sgcc.com.cn/project_list.jsp?site=global&column_code=014001001&project_type=1&company_id=&status=&project_name=&pageNo=1`,
		`http://ecp.sgcc.com.cn/project_list.jsp?site=global&column_code=014001001&project_type=1&company_id=&status=&project_name=&pageNo=2`,
		`http://ecp.sgcc.com.cn/project_list.jsp?site=global&column_code=014001001&project_type=1&company_id=&status=&project_name=&pageNo=3`,
		`http://ecp.sgcc.com.cn/project_list.jsp?site=global&column_code=014001001&project_type=1&company_id=&status=&project_name=&pageNo=4`,
		`http://ecp.sgcc.com.cn/project_list.jsp?site=global&column_code=014001001&project_type=1&company_id=&status=&project_name=&pageNo=5`,
	}
	*/
	//resp, err := http.Get(sgcc_url[0])
	resp, err := http.Get(`https://hq.smm.cn/cj`)
	if err != nil{
		panic(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK{
		fmt.Println("Error:", resp.StatusCode)
		return
	}
	all, err := ioutil.ReadAll(resp.Body)
	if err != nil{
		panic(err)
	}
	//fmt.Printf("%s",all)
	var jg0str = "title=\"长江 1#电解铜\""
	home := strings.Index(string(all), jg0str)
	value := make([]byte,max)
	var i = 0
	for i = 0; i < max; i++{
		value[i] = all[i + home]
	}
	jiage := make([]byte, 50)
	var jg1str = "<span class=\"orange text-r ellipsis change_price\">"
	home = strings.Index(string(value), jg1str)
	for i = 0; i < len(jiage); i++{
		if value[i + home + len(jg1str)] == '<'{
			break
		}
		jiage[i] = value[i + home + len(jg1str)]
	}
	JiaGe(jiage)
	t := time.Now()	//获取当前系统时间
	//fmt.Println(t.String(), "\n长江 1# 电解铜价格：", string(jiage))
	var filename = "./铜排价格记录.txt"
	var f *os.File
	if checkFileIsExist(filename) { //如果文件存在
		f, err = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
	} else {
		f, err = os.Create(filename) //创建文件
	}
	defer f.Close()
	
	f.Write([]byte(t.String()))
	f.Write([]byte("\r\n长江 1# 电解铜价格："))
	f.WriteString(string(jiage[:i]))
	f.Write([]byte("\r\n"))
}

func JiaGe(by []byte){
	for i, data := range by{
		if data > 'a' && data < 'z'{
			by[i] = data - 'i' + '0'
		}
	}
}

/**
 * 判断文件是否存在  存在返回 true 不存在返回false
 */
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}